﻿// <copyright file="MySpacePersonRequest.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2009-03-24</date>
// <summary>MySpace Person Request</summary>

namespace MyOpenSpace
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Windows.Browser;
    using System.Windows.Media.Imaging;
    using Synergist;

    /// <summary>
    /// MySpace Person Request
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SpacePerson", Justification = "this is MySpace.")]
    public class MySpacePersonRequest : INotifyPropertyChanged
    {
        #region Fields
        /// <summary>
        /// the person to request
        /// </summary>
        private string idSpec;

        /// <summary>
        /// the JavaScript object
        /// </summary>
        private MyOpenSpace.Person person;

        /// <summary>
        /// The fields to request
        /// </summary>
        private string requestFields;

        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the MySpacePersonRequest class.
        /// </summary>
        public MySpacePersonRequest()
        {
            if (!HtmlPage.IsEnabled)
            {
                this.AddSampleData();
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Property changed event handler
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the fields to request
        /// </summary>
        [Description("A comma-separated list of field names - use the full name of each field.")] 
        public string RequestFields 
        { 
            get
            {
                return this.requestFields;
            }

            set
            {
                this.requestFields = value;

                this.FetchPerson();
            }
        }

        /// <summary>
        /// Gets or sets the id of the person to query
        /// </summary>
        [Description("opensocial.IdSpec.PersonId.OWNER for the owner's friends\nopensocial.IdSpec.PersonId.VIEWER for viewer's friends")]
        public string IdSpec
        {
            get
            {
                return this.idSpec;
            }

            set
            {
                if (this.idSpec != value)
                {
                    this.idSpec = value;

                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("IdSpec"));
                    }

                    this.FetchPerson();
                }
            }
        }

        /// <summary>
        /// Gets the person specified by IdSpec
        /// </summary>
        public MyOpenSpace.Person Person 
        {
            get
            {
                return this.person;
            }

            private set
            {
                this.person = value;

                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs("Person"));
                }
            }
        }

        #endregion

        #region Implementation

        /// <summary>
        /// Fetches a person
        /// </summary>
        private void FetchPerson()
        {
            if (!HtmlPage.IsEnabled)
            {
                return;
            }

            var os = opensocial.Container.get();

            if (os == null)
            {
                this.AddSampleData();

                return;
            }

            var dataRequest = os.newDataRequest();

            var parameters = new Dictionary<string, object>();

            if (!string.IsNullOrEmpty(this.RequestFields))
            {
                var details = from fieldName in this.RequestFields.Split(',')
                              select fieldName.Trim().Eval() as object;

                parameters["opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS".Eval()] = details.ToArray();
            }

            ////var viewer = new opensocial.IdSpec()
            ////{
            ////    UserId = "opensocial.IdSpec.PersonId.VIEWER".Eval(),
            ////    NetworkDistance = 0
            ////};

            //// var viewer = "opensocial.IdSpec.PersonId.OWNER".Eval();

            var request = os.newFetchPersonRequest(this.IdSpec.Eval(), parameters);

            dataRequest.add(request, this.IdSpec.Eval());

            dataRequest.send(new opensocial.DataReceived(this.OnPersonReceived));
        }

        /// <summary>
        /// Persons are returned
        /// </summary>
        /// <param name="response">the data response</param>
        private void OnPersonReceived(opensocial.DataResponse response)
        {
            if (response.HadError)
            {
                System.Diagnostics.Debug.WriteLine(response.ErrorMessage);

                return;
            }

            var personReturned = new opensocial.Person(response.get(this.IdSpec.Eval()).getData());

            this.Person = new MyOpenSpace.Person(personReturned);
        }

        /// <summary>
        /// Add sample data for testing and offline support
        /// </summary>
        private void AddSampleData()
        {
            if (this.Person != null)
            {
                return;
            }

            var sample = new MyOpenSpace.Person()
            {
                AboutMe = "a Media Experience Evangelist at Microsoft",
                Books = new string[] { "To Kill a Mockingbird\r\nBlink\r\nOutliers" },
                CurrentLocation = new opensocial.Address(null) { PostalCode = "94930" },
                DateOfBirth = new DateTime(1970, 6, 26),
                Heroes = new string[] { "Bill Gates\r\nGary Scherotter\r\nAlbert Einstein" },
                Movies = new string[] { "Cars\r\nWall-E\r\nStar Wars\r\n2001 A Space Odyssey\r\nNorth by Northwest" },
                Nickname = "Michael S. Scherotter",
                ProfileUrl = new Uri("http://www.myspace.com/ms_synergist", UriKind.Absolute),
                ThumbnailImage = new BitmapImage(new Uri("http://c3.ac-images.myspacecdn.com/images02/112/m_3ccd7d71afaa467795c8a5a2d68317a6.jpg", UriKind.Absolute)) 
            };            

            this.Person = sample;
        }
        #endregion
    }
}
